<template>
  <!-- 用户角色列表 -->
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表表格区域 -->
      <el-table border stripe :data="rolesList">
        <!-- 展开列区域 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bd_bottom', i1 === 0 ? 'bd_top': '']"
              type="flex"
            >
              <el-col :span="5" class="center">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 !== 0 ? 'bd_top': '']"
                  type="flex"
                >
                  <el-col :span="4" class="center">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="20">
                    <span v-for="item3 in item2.children" :key="item3.id">
                      <el-tag
                        type="warning"
                        closable
                        @close="removeRightById(scope.row, item3.id)"
                      >{{item3.authName}}</el-tag>
                    </span>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列区域 -->
        <el-table-column type="index" align="center" width="50"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRoleById(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="getRights(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加角色的对话框区域 -->
      <el-dialog title="添加角色" :visible.sync="addRoleDialogVisiable" @close="handleAddDialogClose">
        <el-form
          :model="addRoleForm"
          :rules="editRoleFormRoules"
          ref="addRoleFormRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRoleForm.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRoleForm.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisiable = false">取 消</el-button>
          <el-button type="primary" @click="sureAddRole">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑角色对话框 -->
      <el-dialog title="编辑角色" :visible.sync="editRoleDialogVisiable" @close="handleEditDialogClose">
        <!-- 表单区域 -->
        <el-form
          :model="editRoleForm"
          :rules="editRoleFormRoules"
          ref="editRoleFormRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRoleForm.roleName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRoleForm.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editRoleDialogVisiable = false">取 消</el-button>
          <el-button type="primary" @click="sureEditRoleById">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="rightsDialogVisible" @close="handleRightsDialogClose">
        <!-- 树形控件区域 -->
        <el-tree
          :data="rightsList"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-expand-all="true"
          :default-checked-keys="defaultId"
          ref="rightsTreeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureAddRights">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数组
      rolesList: [],
      // 控制添加角色对话框的显示和隐藏
      addRoleDialogVisiable: false,
      // 添加角色的表单对象
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 控制编辑角色对话框的显示和隐藏
      editRoleDialogVisiable: false,
      // 编辑角色的表单对象
      editRoleForm: {},
      // 编辑角色的表单的验证对象
      editRoleFormRoules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制权限对话框的显示和隐藏
      rightsDialogVisible: false,
      // 权限列表rightsDialogVisible
      rightsList: [],
      // 指定树形控件对应的label和children
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点的id
      defaultId: [],
      // 角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$axios.get('roles')
      // 获取角色列表数据失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！！！')
      }
      // 获取成功
      this.rolesList = res.data
    },
    // 根据角色id和权限id删除对应的权限
    async removeRightById(role, rightId) {
      // 弹框询问用户是否删除
      const confirmResult = await this.MessageBox.confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 取消删除
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      // 执行删除操作
      const { data: res } = await this.$axios.delete(
        `roles/${role.id}/rights/${rightId}`
      )

      // 删除失败
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！！！')
      }
      // 提示成功
      this.$message({
        type: 'success',
        message: res.meta.msg
      })
      // 更新最新的权限
      role.children = res.data
    },
    // 添加角色
    addRole() {
      // 添加角色对话框显示
      this.addRoleDialogVisiable = true
      this.$nextTick(_ => {
        this.$refs['addRoleFormRef'].$el[0].focus()
      })
    },
    // 监听添加角色对话框关闭
    handleAddDialogClose() {
      this.$refs['addRoleFormRef'].resetFields()
    },
    // 监听点击确认按钮添加角色
    sureAddRole() {
      // 表单预验证
      this.$refs['addRoleFormRef'].validate(async valid => {
        console.log(this.addRoleForm)
        if (valid) {
          const { data: res } = await this.$axios.post(
            'roles',
            this.addRoleForm
          )

          // 添加失败
          if (res.meta.status !== 201) {
            return this.$message.error('添加角色失败！！！')
          }

          // 添加成功提示
          this.$message({
            type: 'success',
            message: '添加角色成功'
          })
          // 刷新当前列表
          this.getRolesList()
          // 关闭对话框
          this.addRoleDialogVisiable = false
        }
      })
    },
    // 根据角色id编辑角色信息
    async editRoleById(roleId) {
      // 显示对话框
      this.editRoleDialogVisiable = true
      // 根据角色id获取角色信息
      const { data: res } = await this.$axios.get(`roles/${roleId}`)
      // 获取失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色信息失败！！！')
      }
      // 获取成功
      this.editRoleForm = res.data
    },
    // 监听点击确定按钮修改角色函数
    sureEditRoleById() {
      // 表单预验证
      this.$refs['editRoleFormRef'].validate(async valid => {
        if (valid) {
          const { data: res } = await this.$axios.put(
            `roles/${this.editRoleForm.roleId}`,
            {
              roleName: this.editRoleForm.roleName,
              roleDesc: this.editRoleForm.roleDesc
            }
          )
          // 编辑失败
          if (res.meta.status !== 200) {
            return this.$message.error('编辑角色信息失败！！!')
          }
          // 编辑成功提示
          this.$message({
            type: 'success',
            message: '编辑角色信息成功'
          })
          // 清空编辑表单对象
          this.editRoleForm = {}
          // 重新获取用户列表数据
          this.getRolesList()
          // 关闭对话框
          this.editRoleDialogVisiable = false
        }
      })
    },
    // 处理编辑角色对话框关闭
    handleEditDialogClose() {
      this.$refs['editRoleFormRef'].resetFields()
    },
    // 根据角色id删除角色
    async removeRoleById(roleId) {
      // 提示用户是否删除
      const confirmResult = await this.MessageBox.confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 取消删除
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }

      const { data: res } = await this.$axios.delete(`roles/${roleId}`)

      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      // 删除成功
      this.$message({
        type: 'success',
        message: res.meta.msg
      })
      // 刷新列表
      this.getRolesList()
    },
    // 递归加载当前角色的所有权限
    getLeafKeys(data, arr) {
      if (!data.children) return
      // 遍历当前的数据
      data.children.forEach(item => {
        if (!item.children) {
          return arr.push(item.id)
        }
        this.getLeafKeys(item, arr)
      })
    },
    // 获取所有的权限
    async getRights(role) {
      this.roleId = role.id
      // 显示对话框
      this.rightsDialogVisible = true
      const { data: res } = await this.$axios.get(`rights/tree`)
      // 获取权限数据失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      // 默认选中节点的id
      this.getLeafKeys(role, this.defaultId)
      // 获取成功
      this.rightsList = res.data
    },
    // 监听权限对话框关闭
    handleRightsDialogClose() {
      this.defaultId = []
    },
    // 用户授权
    async sureAddRights() {
      // 获取半选中节点的key
      const halfKeys = this.$refs['rightsTreeRef'].getHalfCheckedKeys()
      // 获取所有选中的叶子节点的key
      const checkKeys = this.$refs['rightsTreeRef'].getCheckedKeys()
      const { data: res } = await this.$axios.post(
        `roles/${this.roleId}/rights`,
        {
          rids: [...checkKeys, ...halfKeys].toString()
        }
      )

      // 分配权限失败
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！！！')
      }
      // 提示
      this.$message({
        type: 'success',
        message: '分配权限成功'
      })
      // 刷新角色列表
      this.getRolesList()
      // 关闭对话框
      this.rightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.center {
  display: flex;
  align-items: center;
}
.bd_top {
  border-top: 1px solid #ebeef5;
}
.bd_bottom {
  border-bottom: 1px solid #ebeef5;
}
.el_row {
  border-top: 1px solid #ebeef5;
  &:last-child {
    border-bottom: 1px solid #ebeef5;
  }
}
.two_rights {
  border-bottom: 1px solid #ebeef5;
  &:last-child {
    border-bottom: none;
  }
}
.el-tag {
  margin-right: 10px;
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>
